package com.liangtian.mdm.dm.attribute.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.dm.attribute.model.Attribute;
import com.liangtian.mdm.dm.attribute.service.AttributeService;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.jsp.controller.JspActionController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 动态模型属性控制类
 *
 * @author hadoop
 */
@Controller
@RequestMapping("/attribute")
public class AttributeController extends BaseController {

    @Autowired
    AttributeService attributeServiceImp;

    @ResponseBody
    @RequestMapping(value = "/queryAllAttr", method = RequestMethod.POST)
    public String quertAllAttr(HttpServletRequest request, Attribute attribute) {
        List<Attribute> returnLst = null;
        try {
//			Map paramMap = RequestUtils.paramToMap(request, Attribute.class);
            attribute.setModelId(request.getParameter("modelId"));
            returnLst = attributeServiceImp.queryAll(attribute);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(returnLst);
    }

    /**
     * <p>TODO 删除属性字段（1.需要清除缓存，2.属性列表本属性需要删除及属性设置和视图设置需要删除
     * 3.已经生成的表中也需要把此属性drop掉）</p>
     * <p>@param request
     * <p>@param attrIds
     * <p>@param modelId
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年6月9日上午11:21:12
     */

    @ResponseBody
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public ResultObject batchDel(HttpServletRequest request, String[] attrIds, String modelId) {
        ResultObject result = null;
        try {
//			ResponseMsg<String> rMsg = new ResponseMsg<String>();
            attributeServiceImp.batchDelAttr(attrIds, modelId);
            result = new ResultObject(1, "删除成功", "删除失败");
//			rMsg.setRspCode(0);
//			jsonObject.put("rmsg", rMsg);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 新增
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addAttr", method = RequestMethod.POST)
    public JSONObject addAttr(HttpServletRequest request, Attribute attribute) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            attributeServiceImp.attrAdd(attribute);
            rMsg.setRspCode(0);

        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 编辑
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editAttr", method = RequestMethod.POST)
    public JSONObject editAttr(HttpServletRequest request, Attribute attribute) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            attributeServiceImp.editAttr(attribute);
            rMsg.setRspCode(0);

        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 校验属性名称
     *
     * @param request
     * @param attribute
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkAttrName", method = RequestMethod.POST)
    public JSONObject checkAttrName(HttpServletRequest request, Attribute attribute) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = attributeServiceImp.checkAttrName(attribute);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 编辑校验属性名称
     *
     * @param request
     * @param attribute
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkAttrNameEdit", method = RequestMethod.POST)
    public JSONObject checkAttrNameEdit(HttpServletRequest request, Attribute attribute) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = attributeServiceImp.checkAttrNameEdit(attribute);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 根据模型ID和属性ID查询某一条属性的具体信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/selectAttrById", method = RequestMethod.POST)
    public JSONObject selectAttrById(Attribute attribute) {
        JSONObject jsonObject = new JSONObject();
        //Map<String, Object> map = RequestUtils.paramToMap(request);
        Attribute attribute2 = new Attribute();
        try {
            attribute2 = attributeServiceImp.selectAttributeById(attribute);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("Attr", attribute2);
        return jsonObject;
    }

    /**
     * 导出属性模板（这个导出属性模板的功能和方法是公用的）
     *
     * @return
     */
    @RequestMapping(value = "attributeExport", method = RequestMethod.GET)
    @ResponseBody
    public void attributeExport(HttpServletResponse response, HttpServletRequest request) {
        attributeServiceImp.attributeExport(response);
    }

    /**
     * 跳转到列表页面
     *
     * @param modelId
     * @param tableName
     * @return
     */
    @RequestMapping(value = "attributeImport", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject attributeImport(HttpServletResponse response, HttpServletRequest request) {
        ResultObject result = null;
        try {
            String modelId = request.getParameter("modelId");
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            InputStream input = file.getInputStream();
            Map<String, Object> resMap = attributeServiceImp.attributeImport(modelId, input);
            boolean success = (boolean) resMap.get("bool");
            if (success) {
                result = new ResultObject(success, "导入成功");
            } else {
                result = new ResultObject(success, (String) resMap.get("err_fileName"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("导入结束");
        return result;
    }

    @RequestMapping(value = "downLoadErr", method = RequestMethod.POST)
    @ResponseBody
    public void downLoadErr(HttpServletResponse response, HttpServletRequest request) {
        String fileName = request.getParameter("err_fileName");
        String path = JspActionController.class.getProtectionDomain().getCodeSource()
                .getLocation().getPath();
        String file = path.substring(1, path.indexOf("/WEB-INF/classes")) + "/error_text/" + fileName;
        //System.out.println("file:"+file);
        try {
            InputStream inStream = new FileInputStream(file);
            //解决中文文件名乱码问题
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            OutputStream output = response.getOutputStream();
            while ((len = inStream.read(b)) > 0)
                output.write(b, 0, len);

            output.flush();
            output.close();
            inStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
